/**
 * Created by helly on 15-2-6.
 */
//浏览器版本
var browser = {};
var ua = navigator.userAgent.toLowerCase();
var browserStr;
(browserStr = ua.match(/msie ([\d]+)/)) ? browser.ie = browserStr[1] :
    (browserStr = ua.match(/firefox\/([\d]+)/)) ? browser.firefox = browserStr[1] :
        (browserStr = ua.match(/chrome\/([\d]+)/)) ? browser.chrome = browserStr[1] :
            (browserStr = ua.match(/opera.([\d]+)/)) ? browser.opera = browserStr[1] :
                (browserStr = ua.match(/version\/([\d]+).*safari/)) ? browser.safari = browserStr[1] : 0;
var isPad = navigator.userAgent.match(/iPad|iPhone|iPod|Android/i) != null;
//isPad = true;
//Prevent memory leaks in IE6
if (browser.ie == 6) {
    window.attachEvent("onunload", function () {
        for (var id in jQuery.cache) {
            if (jQuery.cache[id].handle) {
                try {
                    jQuery.event.remove(jQuery.cache[id].handle.elem);
                } catch (e) {}
            }
        }
    });
}

//不支持placeholder浏览器下对placeholder进行处理
if (document.createElement('input').placeholder !== '') {
    $('[placeholder]').focus(function () {
        var input = $(this);
        if (input.val() == input.attr('placeholder')) {
            input.val('');
            input.removeClass('placeholder');
        }
    }).blur(function () {
        var input = $(this);
        if (input.val() == '' || input.val() == input.attr('placeholder')) {
            input.addClass('placeholder');
            input.val(input.attr('placeholder'));
        }
    }).blur().parents('form').submit(function () {
        $(this).find('[placeholder]').each(function () {
            var input = $(this);
            if (input.val() == input.attr('placeholder')) {
                input.val('');
            }
        });
    });
}

//cookie
(function ($) {
    jQuery.cookie = function (key, value, options) {
        // key and value given, set cookie...
        if (arguments.length > 1 && (value === null || typeof value !== "object")) {
            options = jQuery.extend({}, options);

            if (value === null) {
                options.expires = -1;
            }

            if (typeof options.expires === 'number') {
                var days = options.expires,
                    t = options.expires = new Date();
                t.setDate(t.getDate() + days);
            }

            return (document.cookie = [
                encodeURIComponent(key), '=',
                options.raw ? String(value) : encodeURIComponent(String(value)),
                options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
                options.path ? '; path=' + options.path : '',
                options.domain ? '; domain=' + options.domain : '',
                options.secure ? '; secure' : ''
            ].join(''));
        }

        // key and possibly options given, get cookie...
        options = value || {};
        var result, decode = options.raw ? function (s) {
            return s;
        } : decodeURIComponent;
        return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
    };
})(jQuery);

//tip消息提示
(function ($) {
    jQuery.tipMessage = function (msg, type, time, zIndex, callback) {
        if (typeof tipMessageTimeoutId !== 'number') {
            tipMessageTimeoutId = 0
        }
        if (typeof time !== 'number') {
            time = 2000
        }
        if (typeof zIndex !== 'number' || zIndex == 0) {
            zIndex = 65500
        }
        var $doc = $(document);
        var $win = $(window);
        var $tipMessage = $('#tipMessage');
        var _typeTag = '';
        var _newTop = 0;
        var _newLeft = 0;
        var _width = 0;
        var _NumCount = 1;
        var _mask = "";

        if ($tipMessage.length <= 0) {
            $("body").append('<div id="tipMessage" class="tip_message" ></div>');
            $tipMessage = $('#tipMessage');
        } else {
            if (browser.ie == 6 || browser.ie == 7) {
                $tipMessage.css({
                    width: '99%'
                });
            } else {
                $tipMessage.css({
                    width: 'auto'
                });
            }
        }
        $tipMessage.css({
            opacity: 0,
            zIndex: zIndex
        });
        clearTimeout(tipMessageTimeoutId); //清除旧的延时事件

        if (type == 1) {
            _typeTag = 'hits';
        } else if (type == 2) {
            _typeTag = 'fail';
        } else {
            _typeTag = 'succ';
        }
        if (browser.ie == 6) {
            _mask = '<iframe frameborder="0" scrolling="no" class="ie6_mask"></iframe>';
        }
        $tipMessage.html(_mask + '<div class="tip_message_content"><span class="tip_ico_' + _typeTag + '"></span><span class="tip_content" id="tip_content">' + msg + '</span><span class="tip_end"></span></div>').show();

        //计算top,left 值

        function _calculate() {
            _width = $('#tip_content').width() + 86; //计算tip宽度
            if ($doc.scrollTop() + $win.height() > $doc.height()) {
                _newTop = $doc.height() - $win.height() / 2 - 40;
            } else {
                _newTop = $doc.scrollTop() + $win.height() / 2 - 40;
            }

            if ($win.width() >= $doc.width()) {
                _newLeft = $doc.width() / 2 - _width / 2;
            } else {
                if ($win.width() <= _width) {
                    if ($doc.scrollLeft() + $win.width() + (_width - $win.width()) / 2 > $doc.width()) {
                        _newLeft = $doc.width() - _width;
                    } else {
                        _newLeft = $doc.scrollLeft() + $win.width() / 2 - _width / 2;
                    }
                } else {
                    //alert(1);
                    _newLeft = $doc.scrollLeft() + $win.width() / 2 - _width / 2;

                }
            }
            if (_newLeft < 0) {
                _newLeft = 0;
            }
        }
        _calculate(); //计算top,left 值
        $tipMessage.css({
            top: _newTop,
            left: _newLeft,
            width: _width,
            opacity: 10
        });

        //重置

        function _reSet() {
            _calculate(); //从新计算top,left 值
            $tipMessage.css({
                top: _newTop,
                left: _newLeft,
                width: _width
            });
        }
        //调整大小

        function _resize() {
            if (_NumCount % 2 == 0) { //解决IE6下scrollLeft值问题
                _reSet();
                _NumCount = 1;
            } else {
                ++_NumCount;
            }
        }
        if (!isPad) { //pad设备不支持浮动
            $win.bind({
                "scroll": _reSet,
                "resize": _resize
            });
        }
        tipMessageTimeoutId = setTimeout(function () {
            $tipMessage.remove();
            if (typeof callback == 'function') {
                callback.call();
            }
        }, time);
    };
})(jQuery);


//DIV输入框高度自动调整插件，专处理IE6版
(function(jQuery) {
    jQuery.fn.extend({
        elastic: function(options) {
            var defaults = {
                maxHeight: 1024
            };
            var options = $.extend(defaults, options);
            var mimics = ['paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft', 'fontSize', 'lineHeight', 'fontFamily', 'width', 'fontWeight'];
            return this.each(function() {
                var $obj = $(this),
                    maxheight = parseInt(options.maxHeight, 10) || Number.MAX_VALUE,
                    minheight = parseInt($obj.css('height'), 10) || lineHeight * 3,
                    $twin = jQuery('<div />').css({
                        'position': 'absolute',
                        'display': 'none',
                        'word-wrap': 'break-word',
                        'word-break': 'break-all'
                    });
                $twin.appendTo($obj.parent());
                var i = mimics.length;
                while (i--) {
                    $twin.css(mimics[i].toString(), $obj.css(mimics[i].toString()));
                }

                function update() {
                    var tContent = $obj.html()
                    var twinContent = $twin.html();
                    if (tContent != twinContent) {
                        $twin.html(tContent);
                        if (Math.abs($twin.height() - $obj.height()) > 3) {
                            var goalheight = $twin.height();
                            if (goalheight >= maxheight) {
                                $obj.css({'height': maxheight + 'px', 'overflow-y': 'auto'});
                            }
                            else if (goalheight <= minheight) {
                                $obj.css({'height': minheight + 'px', 'overflow-y': 'hidden'});
                            }
                            else {
                                $obj.css({'height': goalheight + 'px', 'overflow-y': 'hidden'});
                            }
                        }
                    }
                }
                if (browser.ie==6 && !$.support.style) {
                    $obj.css({'overflow-y': 'hidden'});
                    $obj.keyup(function() {
                        update();
                    });
                }
            })
        }
    })
})(jQuery);

//弹出窗
function openMyDialog(str,title){

    var opendiv="<div id='overlay'></div>";
    opendiv+="<div class='opendiv' id='opendiv'>";
    opendiv+="<div class='dnav'>"+title+"</div>";
    opendiv+="<div class='cctop'><a class='close' onClick='closeMyDialog(\"opendiv\")'>X</a></div>";
    opendiv+="<div class='bot'>";
    opendiv+="<div class='openmain'>"+str+"</div>";
    opendiv+="</div>";
    opendiv+="</div>";

    if($("div").hasClass('opendiv')){
        return false;
    }else{
        $(document.body).append(opendiv);
    }

    var pos = 'fixed',
        opendivID=$("#opendiv"),
        overlay=$("#overlay"),
        win_width = $(window).width(),
        win_height = $(window).height(),
        body_height=$(document).height(),
        divwidth=opendivID.width(),
        divHeight=opendivID.height();
    opendivID.css({
        postion: pos,
        top: (win_height-divHeight)/2,
        left: (win_width-divwidth)/2
    });
    overlay.css({
        height: body_height
    });

    $("#overlay").click(function(){
        closeMyDialog("opendiv");
    })
}

//关闭弹出窗
function closeMyDialog(str){
    var div=$("#"+str);
    div.remove();
    $("#overlay").remove();
    return false;

}

//重新刷新页面，使用location.reload()有可能导致重新提交
function reloadPage(win) {
    var location = win.location;
    location.href = location.pathname + location.search;
}

//重新载入页面
function fleshPage(){
    window.location.reload();
}

//页面跳转
function redirect(url) {
    location.href = url;
}

//省市三级联动
function loadRegion(sel,selName,url){
    jQuery("#"+selName+" option").each(function(){
        jQuery(this).remove();
    });
    jQuery("<option value=0>请选择</option>").appendTo(jQuery("#"+selName));
    if(jQuery("#"+sel).val()==0){
        return;
    }
    jQuery.getJSON(url,{pid:jQuery("#"+sel).val()},
        function(data){
            if(data){
                jQuery.each(data,function(idx,item){
                    jQuery("<option value="+item.id+">"+item.name+"</option>").appendTo(jQuery("#"+selName));
                });
            }else{
                jQuery("<option value='0'>请选择</option>").appendTo(jQuery("#"+selName));
            }
        }
    );
}


//新弹出窗口
function newOpenWin(title,content){

    var opendiv="<div id='overlay'></div>";
    opendiv+="<div class='opendiv' id='opendiv'>";
    opendiv+="<div class='dnav'>"+title+"</div>";
    opendiv+="<div class='cctop'><a class='close' onClick='closeMyDialog(\"opendiv\")'>X</a></div>";
    opendiv+="<div class='bot'>";
    opendiv+="<div class='openmain'>"+str+"</div>";
    opendiv+="</div>";
    opendiv+="</div>";

    if($("div").hasClass('opendiv')){
        return false;
    }else{
        $(document.body).append(opendiv);
    }

    var pos = 'fixed',
        opendivID=$("#opendiv"),
        overlay=$("#overlay"),
        win_width = $(window).width(),
        win_height = $(window).height(),
        body_height=$(document).height(),
        divwidth=opendivID.width(),
        divHeight=opendivID.height();
    opendivID.css({
        postion: pos,
        top: (win_height-divHeight)/2,
        left: (win_width-divwidth)/2
    });
    overlay.css({
        height: body_height
    });

    $("#overlay").click(function(){
        closeMyDialog("opendiv");
    })




}